//
//  SettingViewController.m
//  SHHCPhone
//
//  Created by sheng long on 14-6-19.
//  Copyright (c) 2014年 sheng long. All rights reserved.
//

#import "SettingViewController.h"
#import "LocalNotice.h"
#import "SelectPickerView.h"
#import "UpdatePassViewController.h"
#import "FeedBackViewController.h"
#import "AboutViewController.h"
#import "ConsultViewController.h"
#import "PersonalHomePageViewController.h"

#define SHHC_CZTX_TZ            @"SHHC_CZTX_TZSHHC_CZTX_TZ"                     //称重提醒
#define SHHC_CZTX_TZ_TIME       @"SHHC_CZTX_TZ_TIMESHHC_CZTX_TZ_TIME"           //称重时间
#define SHHC_CZTX_TZ_TAG        11

#define SHHC_YQTX_TZ            @"SHHC_YQTX_TZSHHC_YQTX_TZ"                     //孕期提醒

@interface SettingViewController ()<UITableViewDelegate,UITableViewDataSource,SelectPickerViewDelegate,UIAlertViewDelegate>
{
    NSArray *dataArray;
    
    UITableView *mainTable;
}
@end

@implementation SettingViewController

-(void)dealloc
{
    [[NSNotificationCenter defaultCenter ] removeObserver:self];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [[NSNotificationCenter defaultCenter ] addObserver:self selector:@selector(reloadData) name:BLUETOOTHMANAGER_LJSBCG object:nil];
    [[NSNotificationCenter defaultCenter ] addObserver:self selector:@selector(reloadData) name:BLUETOOTHMANAGER_LJSBSB object:nil];
    [[NSNotificationCenter defaultCenter ] addObserver:self selector:@selector(reloadData) name:BLUETOOTHMANAGER_STATE_CHANGE object:nil];
    
    [self.view setBackgroundColor:GET_COLOR(@"f7f7f7")];
    
    if (![APP_USERDEFAULTS valueForKey:SHHC_CZTX_TZ_TIME]) {
        [APP_USERDEFAULTS setValue:@"10:00" forKey:SHHC_CZTX_TZ_TIME];
    }
    
    [navigationBarView setTitle:@"设置"];
    [navigationBarView setNormalLeftButton];
    
//    dataArray = [[NSArray alloc] initWithObjects:@{@"":@[@"个人主页",@"修改密码"]},@{@"称重提醒":@[@"通知",@"接收通知时间"]},@{@"其他":@[@"意见反馈",@"检查更新",@"关于我们"]}, nil];
    
    mainTable = [[UITableView alloc] initWithFrame:CGRectMake(0, NAVIGATIONBAR_HEIGHT, CURRENT_CONTENT_WIDTH, CURRENT_CONTENT_HEIGHT-NAVIGATIONBAR_HEIGHT)];
    [self.view addSubview:mainTable];
    [mainTable setBounces:NO];
    [mainTable setBackgroundColor:[UIColor clearColor]];
    [mainTable setSeparatorColor:[UIColor clearColor]];
    [mainTable setDelegate:self];
    [mainTable setDataSource:self];
    
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, mainTable.frame.size.width, 90)];
    UIButton *button = [OftenMenthod setButtonTitle:@"退出登录"];
    [button setCenter:CGPointMake(view.frame.size.width/2, view.frame.size.height/2)];
    [button addTarget:self action:@selector(exitButt) forControlEvents:UIControlEventTouchUpInside];
    [view addSubview:button];
    [mainTable setTableFooterView:view];
    
    [self showTime];
}

-(void)leftButtonClick
{
    [self.navigationController popToRootViewControllerAnimated:YES];
}

-(void)switchChange:(UISwitch*)sw
{
    CLog(@"改变switch");
    if (sw.tag == SHHC_CZTX_TZ_TAG) {
        //称重提醒
        [APP_USERDEFAULTS setObject:[NSNumber numberWithBool:sw.on] forKey:SHHC_CZTX_TZ];
        if (sw.on) {
            NSString *time = [APP_USERDEFAULTS valueForKeyPath:SHHC_CZTX_TZ_TIME];
            [LocalNotice setColock:[z_DateTime dencodeTime:time format:@"HH:mm"]];
        }else{
            [LocalNotice cancelClolck];
        }
        [self showTime];
    }else{
        [APP_USERDEFAULTS setObject:[NSNumber numberWithBool:sw.on] forKey:SHHC_YQTX_TZ];
    }
}

-(void)exitButt
{
    CLog(@"退出登录");
    //清除登录信息
    [APP_USERDEFAULTS removeObjectForKey:APP_LOGIN_SUCESS_SVAE_MSG];
    [self.mm_drawerController.navigationController popToRootViewControllerAnimated:YES];
}

//是否显示提醒时间
-(void)showTime
{
    BOOL show = [[APP_USERDEFAULTS objectForKey:SHHC_CZTX_TZ] boolValue];
    if (show) {
        dataArray = [[NSArray alloc] initWithObjects:@{@"":@[@"个人主页",@"修改密码"]},@{@"称重提醒":@[@"通知",@"接收通知时间"]},@{@"其他":@[@"手动打开蓝牙",@"健康秤清零",@"意见反馈",@"检查更新",@"关于我们"]}, nil];
    }else{
        dataArray = [[NSArray alloc] initWithObjects:@{@"":@[@"个人主页",@"修改密码"]},@{@"称重提醒":@[@"通知"]},@{@"其他":@[@"手动打开蓝牙",@"健康秤清零",@"意见反馈",@"检查更新",@"关于我们"]}, nil];
    }
    
    if (APP_BLUEMANAGER.CBManager.state == CBCentralManagerStatePoweredOn) {
        //蓝牙已开启
    }else{
        
    }
    
    if ([APP_BLUEMANAGER.bleModel.bleManager isConnected] == YES) {
        //已连接设备
    }else{
        
    }
    
    [mainTable reloadData];
}

-(void)reloadData
{
    [mainTable reloadData];
}

#pragma mark - UITableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return dataArray.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    NSString *text = [[[dataArray objectAtIndex:section] allKeys] lastObject];
    return text.length==0?6:35;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    NSString *text = [[[dataArray objectAtIndex:section] allKeys] lastObject];
    
    CGFloat height = 35;
    if (text.length==0) {
        height = 6;
    }
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, tableView.frame.size.width, height)];
    [view setBackgroundColor:GET_COLOR(@"f7f7f7")];
    
    if (text.length > 0) {
        UILabel *label1 = [[UILabel alloc] init];
        [label1 setText:text];
        [view addSubview:label1];
        [label1 setTextColor:GET_COLOR(@"a2a2a2")];
        [label1 setBackgroundColor:[UIColor clearColor]];
        [label1 setFont:[UIFont systemFontOfSize:12]];
        [label1 sizeToFit];
        [label1 setCenter:CGPointMake(18+label1.frame.size.width/2, view.frame.size.height-6-label1.frame.size.height/2)];
    }
    
    UIView *view1 = [[UIView alloc] initWithFrame:CGRectMake(0, view.frame.size.height-.5, view.frame.size.width, .5)];
    [view1 setBackgroundColor:GET_COLOR(@"dfdfdf")];
    [view addSubview:view1];
    
    return view;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [[[[dataArray objectAtIndex:section] allValues] lastObject] count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString * cellId = @"UITableViewCell";
    UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:cellId];
    if (!cell) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellId];
        [cell setBackgroundColor:[UIColor whiteColor]];
        [cell.textLabel setFont:[UIFont boldSystemFontOfSize:14]];
        
        [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
        
        UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, cell.frame.size.height-.5, cell.frame.size.width, .5)];
        [view setBackgroundColor:GET_COLOR(@"dfdfdf")];
        [cell addSubview:view];
    }
    NSArray *array = [[[dataArray objectAtIndex:indexPath.section] allValues] lastObject];
    [cell.textLabel setText:[array objectAtIndex:indexPath.row]];
    [cell.textLabel setTextColor:GET_COLOR(@"3e3e3e")];

    //是否需要选中背景色
    BOOL selected = YES;
    switch (indexPath.section) {
        case 2:
        {
            if ((indexPath.row == 0 && APP_BLUEMANAGER.CBManager.state == CBCentralManagerStatePoweredOn) || (indexPath.row == 1 && [APP_BLUEMANAGER.bleModel.bleManager isConnected] == NO)) {
                [cell.textLabel setTextColor:[UIColor lightGrayColor]];
                selected = NO;
            }
        }
        case 0:
        {
            [cell setAccessoryView:nil];
        }
            break;
        case 1:
        {
            if (indexPath.row == 1) {
                UILabel *label1 = [[UILabel alloc] init];
                [label1 setText:[APP_USERDEFAULTS valueForKey:SHHC_CZTX_TZ_TIME]];
                [label1 setTextColor:GET_COLOR(@"cfcfcf")];
                [label1 setBackgroundColor:[UIColor clearColor]];
                [label1 sizeToFit];
                [cell setAccessoryView:label1];
            }else{
                UISwitch *sw = [self getSwitch:[[APP_USERDEFAULTS objectForKey:SHHC_CZTX_TZ] boolValue]];
                [sw setTag:SHHC_CZTX_TZ_TAG];
                [cell setAccessoryView:sw];
                selected = NO;
            }
            break;
        }
        default:
        {

        }
            break;
    }
    
    if (selected) {
        [cell setSelectionStyle:UITableViewCellSelectionStyleDefault];
        UIView *view1 = [[UIView alloc] initWithFrame:cell.bounds];
        [view1 setBackgroundColor:GET_COLOR(@"d9d9d9")];
        [cell setSelectedBackgroundView:view1];
    }else{
        [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
        [cell setSelectedBackgroundView:nil];
    }
    
    return cell;
}

-(UISwitch*)getSwitch:(BOOL)on
{
    UISwitch *sw = [[UISwitch alloc] init];
    [sw setOnTintColor:GET_COLOR(@"febad3")];
    [sw setOn:on];
    [sw addTarget:self action:@selector(switchChange:) forControlEvents:UIControlEventValueChanged];
    return sw;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    switch (indexPath.section) {
        case 0:
        {
            switch (indexPath.row) {
                case 1:
                {
                    UpdatePassViewController *view = [[UpdatePassViewController alloc] init];
                    [self.navigationController pushViewController:view animated:YES];
                }
                    break;
                default:
                {
                    PersonalHomePageViewController *view = [[PersonalHomePageViewController alloc] init];
                    [self.navigationController pushViewController:view animated:YES];
                }
                    break;
            }
        }
            break;
        case 1:
        {
            if (indexPath.row==1) {
                SelectPickerView *dateView = [[SelectPickerView alloc] initWithFrame:self.view.bounds];
                [dateView setDelegate:self];
                [dateView setShowView:SZ_CZTX_TZ text:[APP_USERDEFAULTS valueForKeyPath:SHHC_CZTX_TZ_TIME]];
                [self.view addSubview:dateView];
            }
        }
            break;
        case 2:
        {
            if (indexPath.row == 0) {
                if (APP_BLUEMANAGER.CBManager.state != CBCentralManagerStatePoweredOn) {
                    //打开蓝牙
                    [APP_BLUEMANAGER connectCBManager];
                }
            }else if (indexPath.row==1) {
                if ([APP_BLUEMANAGER.bleModel.bleManager isConnected] == YES) {
                    //体脂称清零
                    [LoadingFrameView showLabelLoadingview:@"正在清零..."];
                    [self performSelector:@selector(resetSuccess) withObject:nil afterDelay:1];
                    [APP_BLUEMANAGER.bleModel cleanUserMsg];
                }
            }else if (indexPath.row==2) {
                ConsultViewController *view = [[ConsultViewController alloc] init];
                view.consultType = FEEDBACK_TYPE;
                [self.navigationController pushViewController:view animated:YES];
            }else if (indexPath.row==3){
                //检查更新
                [self checkUpdate];
            }else if (indexPath.row==4){
                AboutViewController *view = [[AboutViewController alloc] init];
                [self.navigationController pushViewController:view animated:YES];
            }
        }
            break;
        default:
            break;
    }
}

-(void)resetSuccess
{
    [LoadingFrameView autoDisappearBlockingview:@"清零成功"];
}

-(void)checkUpdate
{
    [LoadingFrameView autoDisappearBlockingview:@"此版本为最新版本"];
    return;
    
    if (!CURRENT_NETWORK_STATE) {
        [LoadingFrameView autoDisappearBlockingview:@"请检查您的网络连接"];
        return;
    }
    
    [LoadingFrameView showLoadingview];
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSDictionary *infoDic = [[NSBundle mainBundle] infoDictionary];
        NSString *currentVersion = [infoDic objectForKey:@"CFBundleVersion"];
        NSString *URL = [NSString stringWithFormat: @"http://itunes.apple.com/lookup?id=%@",AppleID];
        
        ASIHTTPRequest *request =  [z_Network httpPostValue:nil Url:URL Delegate:self Tag:0];
        [request startSynchronous];
        NSError *error = [request error];
        //网络状态正常
        if (!error){
            //获取服务器返回值
            NSDictionary *dic = [[request responseString] objectFromJSONString];
            NSArray *infoArray = [dic objectForKey:@"results"];
            if ([infoArray count]) {
                NSDictionary *releaseInfo = [infoArray objectAtIndex:0];
                NSString *lastVersion = [releaseInfo objectForKey:@"version"];
                dispatch_async(dispatch_get_main_queue(), ^{
                    if (![lastVersion isEqualToString:currentVersion]) {
                        [LoadingFrameView directlyDisappear];
                        CLog(@"");
                        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"更新" message:@"有新的版本更新，是否前往更新？" delegate:self cancelButtonTitle:@"关闭" otherButtonTitles:@"更新", nil];
                        alert.tag = 10000;
                        [alert show];
                    }else{
                        [LoadingFrameView autoDisappearBlockingview:@"此版本为最新版本"];
                    }
                });
                return;
            }
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            [LoadingFrameView autoDisappearBlockingview:@"获取更新失败"];
        });
    });
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    CLog(@"buttonIndex===%d",buttonIndex);
    if (buttonIndex==1) {
        NSURL *url = [NSURL URLWithString:@"https://itunes.apple.com"];
        [[UIApplication sharedApplication]openURL:url];
    }
}

#pragma mark - SelectPickerViewDelegate
-(void)selectedText:(NSString*)text
{
    if (![[APP_USERDEFAULTS valueForKey:SHHC_CZTX_TZ_TIME] isEqualToString:text]) {
        [APP_USERDEFAULTS setValue:text forKeyPath:SHHC_CZTX_TZ_TIME];
        [mainTable reloadData];
        
        if ([[APP_USERDEFAULTS objectForKey:SHHC_CZTX_TZ] boolValue]) {
            //称重提醒开启，重新设置提醒闹钟
            [LocalNotice cancelClolck];
            [LocalNotice setColock:[z_DateTime dencodeTime:text format:@"HH:mm"]];
        }
    }
}


@end
